<?php
session_start();
Header("content-type: application/x-javascript");
require 'connection.php';
require 'util.php';
$query = "SELECT result.pk, result.title, result.image_url, result.description, result.price, location.latitude, location.longitude FROM result INNER JOIN address on result.address_fk = address.pk INNER JOIN location ON address.location_fk = location.pk";
$resultArray = getResultArray($query, $pdo);
$jsArray = Array();
$ids = Array();
foreach($resultArray as $r){
	$jsArray[]=getJsonScriptFromResut($r);
	$ids[] = $r['pk'];
}
?>
function Results(resultArray, mapCanvas, placeInput){
  this.resultArray = resultArray;
  this.openedInfoBoxResultId = "";
  /*Creates a the map*/
  this.createMap = function(lat, lon){
    var myLatLng = new google.maps.LatLng(lat, lon);
    var mapOptions = {
        center: myLatLng,
        zoom: 13
      };
    var map = new google.maps.Map(mapCanvas, mapOptions); 
    return map;
  };
 
  this.createMarkers = function(resultArray, map){
    debugger;
    var markers = {};
    for(var i in resultArray){
      if(!resultArray.hasOwnProperty(i)){
        continue;
      }
      var myLatLng = new google.maps.LatLng(resultArray[i].position.latitude, resultArray[i].position.longitude);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
      });
      marker.setIcon(/** @type {google.maps.Icon} */({
      url: resultArray[i].iconImage.path,
      size: new google.maps.Size(resultArray[i].iconImage.width, resultArray[i].iconImage.height),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(resultArray[i].iconImage.scaledWidth, resultArray[i].iconImage.scaledHeight)
      }));
      marker.setVisible(true);
      markers[resultArray[i].id] = marker;
      resultArray[i].marker = marker;
      resultArray[i].infoWindow = new InfoBox({
         content: resultArray[i].infoWindowString,
         disableAutoPan: false,
         maxWidth: resultArray[i].infoWindowData.width,
         pixelOffset: new google.maps.Size(resultArray[i].infoWindowData.pixelOffset.x, resultArray[i].infoWindowData.pixelOffset.y),
         //pixelOffset: new google.maps.Size(0, 0),
         zIndex: null,
         boxStyle: {},
        closeBoxMargin: "",
        closeBoxURL: "",
        infoBoxClearance: new google.maps.Size(1, 1)
    });
    var infobox = resultArray[i].infoWindow;
    var thisObj = this;
    var openInfoBox = function(i) {
        thisObj.closeInfoBox();
        var m = resultArray[i].marker;
        debugger;
        resultArray[i].infoWindow.open(map, m);
        m.setVisible(false);
        thisObj.openedInfoBoxResultId = i;
    };
    var addEvent = function(i){
      google.maps.event.addListener(resultArray[i].marker, 'click', function(){openInfoBox(i);});
    };

    addEvent(i);
    }
    return markers;
  };

  this.createClusters = function(markers, map){
    var mcOptions = {gridSize: 50, maxZoom: 15};
    var markersArray = [];
    for(var key in markers){
      var i = 0;
      if(markers.hasOwnProperty(key)){
        markersArray[i++] = markers[key];
      }
    }
    var mc = new MarkerClusterer(map, markers, mcOptions);
  };

  this.createAutoComplete = function(map, placeInput){
      var autocomplete = new google.maps.places.Autocomplete(placeInput);
      google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.geometry) {
        return;
      }
      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }
      var marker = new google.maps.Marker({
        position: null,
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
      });
      marker.setIcon(/** @type {google.maps.Icon} */({
        url: "img/marker.png",
        size: new google.maps.Size(30, 54),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(13, 24),
        scaledSize: new google.maps.Size(13, 24)
      }));
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

      var address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
      infowindow.open(map, marker);
    });
    return this.autocomplete;
  };

  this.goTo = function(lat, lon, map, markerId){
    debugger;
    var latlon = new google.maps.LatLng(lat, lon);
    var thisObj = this;
    map.setCenter(latlon);
  };

  this.addGoTo = function(result, map){
  	debugger;
    var mapLinkATagId = "#"+result.mapLinkId;
    var thisObj = this;
    $(mapLinkATagId).click(function(){thisObj.goTo(result.position.latitude, result.position.longitude, thisObj.map, result.id);});
  };

  this.initialize = function(userLocation){
    debugger;
    this.userPosition = userLocation;
    this.map = this.createMap(this.userPosition.latitude, this.userPosition.longitude);
    var thisObj = this;
    google.maps.event.addListener(this.map, 'zoom_changed', function() {
        thisObj.closeInfoBox();
    });
    this.markers = this.createMarkers(resultArray, this.map);
    this.createClusters(this.markers, this.map);
    if(placeInput != null){
      this.createAutoComplete(this.map, placeInput);
    }
    for(var o in resultArray){
      if(!resultArray.hasOwnProperty(o)){
        continue;
      }
      this.addGoTo(resultArray[o], this.map);
    }
    var thisObj = this;
    var setUserLocation = function(pos){
      debugger;
      if(!pos){
        pos = {
          coords: {latitude: 51.524979,
          longitude: -0.129304}
        };
      }
      thisObj.userLocation = pos.coords;
      var myLatLng = new google.maps.LatLng(thisObj.userLocation.latitude, thisObj.userLocation.longitude);
      thisObj.map.setCenter(myLatLng);
    };
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(pos){setUserLocation(pos);});
    }
  };

  this.closeInfoBox = function(){
    debugger;
    if(this.openedInfoBoxResultId === ""){
      return;
    }
    var theInfoBoxOpened = this.resultArray[this.openedInfoBoxResultId].infoWindow;
    var theMarkerHidden = this.resultArray[this.openedInfoBoxResultId].marker;
    theInfoBoxOpened.close();
    theMarkerHidden.setVisible(true);
  };
}

function logout(){
  var form = document.getElementById("logoutForm");
  form.submit();
}

function load(){
  debugger;
<?php
	foreach ($jsArray as $element) {
		echo $element;
	}
?>
var resultArray = {};
<?php
	foreach ($ids as $id) {
    $hiddenPk = getHiddenListingPk($id);
		echo "resultArray[result{$hiddenPk}.id] = result{$hiddenPk};";
	}
?>

var userLocation = {
  latitude: 51.524979,
  longitude: -0.129304
};
debugger;
 /*Retrieves the user location*/

  var mapCanvas = document.getElementById('map-canvas');
  var placeInput = document.getElementById('place-input');
  window.results = new Results(resultArray, mapCanvas, placeInput);
  results.initialize(userLocation);
  var center = results.map.getCenter();
  debugger;
}
google.maps.event.addDomListener(window, 'load', load);

function openInfoWindow(id){
  window.results.resultArray[id].infowindow.open(window.results.map, window.results.resultArray[id].marker);
  window.results.resultArray[id].markerWindow.close();
}

var clicked = false;
$(document).ready(function(){
  var minPrice=100;
  var maxPrice=2500;
  var minDistance = 0;
  var maxDistance = 100;
  var changeButtonColor = function(child){
    $(child).parent().children().each(function(){
    $(this).removeClass("blueButton2").addClass("blueButton");
    });
    $(child).addClass("blueButton2");

    if($(child).index() == 0){
      $("#arrow").css("left","150px");
    }else if($(child).index() == 1){
      $("#arrow").css("left","230px");
    }else if($(child).index() == 2){
      $("#arrow").css("left","310px");
    }else if($(child).index() == 3){
      $("#arrow").css("left","390px");
    }
  };
  var showFilters = function(){
    $("#arrow").slideDown(0);
    $("#menu").slideDown(200);
   };
   var hideFilters = function(){
    if ((!$("#ui-datepicker-div").is(":visible") || $("#ui-datepicker-div").html() == "") && $("#n")) {
       $("#menu").slideUp(200);
       $("#arrow").slideUp(200);
    }
   };
   var changePriceValue = function(inputRange, inputTextPriceValueID){
      var inputRangeValue = parseInt($(inputRange).val());
      $(inputTextPriceValueID).removeAttr('readonly');
      $(inputTextPriceValueID).val("£"+(minPrice + maxPrice * (inputRangeValue/100)).toFixed(0));
      $(inputTextPriceValueID).attr('readonly','readonly');
   };

  $("#left-buttons-container").children().each(function (){
    $(this).click(function(){changeButtonColor($(this));
    });
  });
  function displayOrCloseMenu(){
    if(clicked == false){
      $("#controller1 > div > span:first-child").html("CLOSE");
      $("#controller1 > div > span:first-child").addClass("closeClass");
      $("#search-button-container").css("background-image","url('img/search_icon_black.png')");
      $("#search-button-container").css("position","relative");
      $("#search-button-container").css("bottom","-4px");
      showFilters();
      clicked = true;
    }else{
      $("#controller1 > div > span:first-child").html("SEARCH");
      $("#controller1 > div > span:first-child").removeClass("closeClass");
      $("#search-button-container").css("background-image","url('img/search_icon.png')");
      $("#search-button-container").css("bottom","0");
      hideFilters();
      clicked = false;
    }
  }
  $("#search-button-container").click(displayOrCloseMenu);
  $("#search-text").click(displayOrCloseMenu);
  $("#date input[type='text']").each(function(){$(this).datepicker({  
            inline: true,  
            showOtherMonths: true,  
            dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],  
        });});

  var initialPriceValue = parseInt($("#input-range-price").val());
  $("#input-range-price + p").width(170*(initialPriceValue/100));
  $("#priceValue").attr("value","£"+(minPrice + maxPrice * (initialPriceValue/100)));
  $("#priceValue").attr('readonly','readonly');
  $("#input-range-price").on("input change", function(){
    changePriceValue($(this), "#priceValue");
  });

  $("#all").change(function(){
    if($("#all").prop('checked') == true){
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', true);
        });
    }else{
        $("#menu input[type='checkbox']").each(function(){
          $(this).prop('checked', false);
        });
    }
  });

  $('input[type="range"]').change(function () {
    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
    
    $(this).css('background-image',
                '-webkit-gradient(linear, left top, right top, '
                + 'color-stop(' + val + ', black), '
                + 'color-stop(' + val + ', #979797)'
                + ')'
                );
    $(this).css('background-image',
                '-moz-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
    $(this).css('background-image',
                '-ms-linear-gradient(left, '
                + 'black ' + (val*100) + '%, '
                + '#979797 ' + 0 + '%'
                + ')'
                );
});
var resultMoreInfoToClose = null;
$("a[id^=moreInfoButton]").each(function(){
  var thisObj = this;
  $(thisObj).click(function(){
    if($(thisObj).html() === "MORE INFO"){
      if(resultMoreInfoToClose){
        $(resultMoreInfoToClose).html("MORE INFO");
      } 
      getAdditionalInformation(thisObj);
      
      $(thisObj).html("CLOSE");
      resultMoreInfoToClose = thisObj;
    }else{
      $("#moreInfoPanel").css('left', "1300px");
      $(this).html("MORE INFO");
      $("#moreInfoPanel > div").css("display","none");
      $("#moreInfoPanel > div").css("opacity", "0");
      resultMoreInfoToClose = null;
    }
  });
});

function getAdditionalInformation(element){
  debugger;
  var resultId = $(element).attr("id");
  var url = getURL("getAdditionalInformation.php");
  var addOnclickShowLink = function(){
    var opened = false;
    var showHideUserInfo = function(){
      
      if(opened){
        $(this).html("Show user info");
        $("#userInfo").css("display", "none");
      }else{
        $(this).html("Close user info");
        $("#userInfo").css("display", "block");
      }
      opened = !opened;
    };
    $($("#listingInfo a")[0]).on("click", showHideUserInfo);
  };
  var showAdditionalInfo = function(r){
    $("#moreInfoPanel").html(r);
    addOnclickShowLink();
  };

  $.post(url, {id: resultId} ,showAdditionalInfo);
  $("#moreInfoPanel").css('left',"640px");
  $("#moreInfoPanel > div").css("display","block");
  $("#moreInfoPanel > div").css("opacity", "1");
}

var showLoginWindow = function(){
    showLoadingLayer();
    var responseFunction = function(r)
    {
        hideLoadingLayer();
        r = JSON.parse(r);
        $(this).html(r.buttonString);
        if(!r.htmlString.trim() == "")
        {
          debugger;
          executeLoginJS(r);
        }
    };
    var url = getURL("login.php");
    $.post(url, {} ,responseFunction);
};
$("#loginButton").on("click", showLoginWindow);
debugger;
  <?php
    if(checkUserLoggedIn()){
      echo "debugger;showProfieAndLogoutButtons();";
    }
  ?>

});

function addGoToProfile(){
  debugger;
  if($("#profileButton").length == 0){
    var profileButtonString = "<a id=\"profileButton\" href=\"#\" class=\"grayButton2\">Profile</a>";
    $("#loginButton").before(profileButtonString);    
  }
  $("#profileButton").on("click", function(){
    showLoadingLayer();
    debugger;
    var processResponse = function(r){
      var json = JSON.parse(r);
      if(json){
        if(json.response){
          $.post(url, {action: "showProfile"}, displayProfile);
        }else{
          configureLoginLayer(json);
          initializeProfileCompletion();
        }
      }
    };
    var params = {
      action: "requestProfile"
    };
    var url = getURL("profile.php");
    $.post(url, params, processResponse);    
  });
}
  